package com.cskaoyan.controller.wx;

import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.wx.auth.bo.LoginBo;
import com.cskaoyan.bean.wx.auth.bo.PhoneBo;
import com.cskaoyan.bean.wx.auth.bo.RegisterBo;
import com.cskaoyan.bean.wx.auth.bo.ResetBo;
import com.cskaoyan.bean.wx.auth.vo.LoginVo;
import com.cskaoyan.bean.wx.auth.vo.UserInfoVo;
import com.cskaoyan.config.AliyunComponent;
import com.cskaoyan.config.CskaoyanSessionManager;
import com.cskaoyan.realm.MallToken;
import com.cskaoyan.service.wx.WxAuthService;
import com.cskaoyan.util.Md5utils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @Name : AuthController.java
 * @Time : 2021/8/14 13:51
 * @Author : creamycandy
 * @Software : IntelliJ IDEA
 */

@RestController
@RequestMapping("wx/auth")
public class WxAuthController {

    private Long start;
    private Long end;
    private Map<String,String> phoneCode;

    @Autowired
    WxAuthService wxAuthService;

    @Autowired
    AliyunComponent aliyunComponent;

    @Autowired
    CskaoyanSessionManager sessionManager;

    @RequestMapping("login")
    public BaseRespVo login(@RequestBody LoginBo loginBo) {
//        UserInfoVo userInfoVo = new UserInfoVo();
//        userInfoVo.setNickName(loginBo.getUsername());
//        userInfoVo.setAvatarUrl("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/80/h/80");
//        LoginVo loginVo = new LoginVo();
//        loginVo.setUserInfo(userInfoVo);
//        loginVo.setTokenExpire(new Date(System.currentTimeMillis()));
//        loginVo.setToken("uysl5zz3mhih5f2ev1cwfl1oarf6m0l8");
        if(!wxAuthService.login(loginBo.getUsername())){
            return BaseRespVo.fail("3次密码错误，请三十秒后重新登录！");
        }
        String type = "wx";
        String password = Md5utils.getMd5Result(loginBo.getPassword());
        MallToken token = new MallToken(loginBo.getUsername(), password, type);
        Subject subject = SecurityUtils.getSubject();
        UserInfoVo userInfo = wxAuthService.getUserInfo(loginBo.getUsername());
        LoginVo loginVo = new LoginVo();
        loginVo.setUserInfo(userInfo);
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            wxAuthService.loginWrong(loginBo.getUsername());
            return BaseRespVo.fail("用户名或密码不正确");
        }
        Session session = subject.getSession();
        String tokenVo = session.getId().toString();
        loginVo.setToken(tokenVo);
        loginVo.setTokenExpire(new Date(System.currentTimeMillis()));
        wxAuthService.loginSuccess(loginBo.getUsername());
        return BaseRespVo.ok(loginVo);
    }


    @RequestMapping("logout")
    public BaseRespVo logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return BaseRespVo.ok();
    }

    @RequestMapping("regCaptcha")
    public BaseRespVo regCaptcha(@RequestBody PhoneBo phoneBo) {
        StringBuffer random = new StringBuffer();
        for (int i = 0; i < 6; i++) {
            int num = (int) (1 + Math.random() * (9));
            random.append(num);
        }
        phoneCode = new HashMap<>();
        String code = random.toString();
        aliyunComponent.sendMsg(phoneBo.getMobile(), code);
        start = System.currentTimeMillis();
        String phoneNum = phoneBo.getMobile();
        phoneCode.put(phoneNum,code);
        return BaseRespVo.ok();
    }

    @RequestMapping("register")
    public BaseRespVo register(@RequestBody RegisterBo registerBo) {
        end = System.currentTimeMillis();
        if (end - start > 300000) {
            return BaseRespVo.fail("验证码失效~");
        }
        if (!registerBo.getCode().equals(phoneCode.get(registerBo.getMobile()))) {
            return BaseRespVo.fail("验证码错误~");
        }
        Integer register = wxAuthService.register(registerBo);
        if (register == 0) {
            return BaseRespVo.fail("该手机号已注册~");
        } else if (register == 1) {
            return BaseRespVo.fail("用户名已存在~");
        }
        String password = Md5utils.getMd5Result(registerBo.getPassword());
        MallToken token = new MallToken(registerBo.getUsername(), password,"wx");
        Subject subject = SecurityUtils.getSubject();
        UserInfoVo userInfo = wxAuthService.getUserInfo(registerBo.getUsername());
        LoginVo loginVo = new LoginVo();
        loginVo.setUserInfo(userInfo);
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            return BaseRespVo.fail("用户名或密码不正确");
        }
        Session session = subject.getSession();
        String tokenVo = session.getId().toString();
        loginVo.setToken(tokenVo);
        loginVo.setTokenExpire(new Date(System.currentTimeMillis()));
        return BaseRespVo.ok(loginVo);
    }

    @RequestMapping("reset")
    public BaseRespVo reset(@RequestBody ResetBo resetBo) {
        String code = phoneCode.get(resetBo.getMobile());
        if (code == null || "".equals(code)) {
            return BaseRespVo.fail("验证码失效~");
        }
        if (!resetBo.getCode().equals(code)) {
            return BaseRespVo.fail("验证码错误~");
        }
        Integer reset = wxAuthService.reset(resetBo);
        if (reset == 0) {
            return BaseRespVo.fail("该用户不存在~");
        }
        return BaseRespVo.ok("密码修改成功！");
    }
}
